package com.cc.main.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.cc.main.Const;
import com.cc.main.cmd.AddKeywordCmd;
import com.cc.main.cmd.PathCmd;
import com.cc.main.cmd.SettimeCmd;
import com.cc.main.problems.BaseFilter;
import com.cc.main.problems.DeleteKeyword;
import com.cc.main.problems.bean.CmdBean;
import com.cc.main.problems.bean.KeyWordItem;

public class MyUtils {
	
	static Scanner scanner = new Scanner(System.in);
	private static String preLine = "";//当前扫描行的前一行数据
	/**
	 * 获取用户输入的内容
	 * @return 返回输入的内容
	 */
	public static String getInput(String tag) {
		String mInput = "";
		System.out.print(tag + "# ");
		if(scanner.hasNextLine()) {
			mInput = scanner.nextLine();
		}
		return mInput;
	}
	public static void releaseInput() {
		scanner.close();
	}
	
	/**
	 * str 是否时数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str){
		for (int i = 0; i < str.length(); i++){
			if (!Character.isDigit(str.charAt(i))){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 获取符合条件的日志
	 * @param f 是否格式化检测
	 * @param path
	 * @return
	 */
	public static List<String> getFileList(boolean bf,String path){
		List<String> list = new ArrayList();
		File file = new File(path);
		if(file.isFile()) {
			if(bf) {
				//panel.log.1_2022-06-25-17-21-37-000.log
//				if(file.getName().startsWith(Const.LOG_FILE_SUFFIX) && file.getName().length() > 35) {
				if(file.getName().contains(Const.LOG_FILE_SUFFIX)) {
	            	list.add(file.getAbsolutePath());
	            }
			}else {
				list.add(file.getAbsolutePath());
			}
		}else {
			File[] children = file.listFiles();
	        if (children == null) {
	            return list;
	        }else {
	            for(File f:children) {
	                List<String> tlist = getFileList(bf,f.getAbsolutePath());
	                list.addAll(tlist);
	            }
	        }
		}
        
		return list;
	}
	
	/**
	 * 筛选日志
	 * @param kwList 默认关键字列表
	 * @param fileList 日志路径列表
	 * @param addKwList 新添加的关键字
	 * @param keyTimeList 设置的时间范围
	 * @return 返回过滤的内容
	 * @throws IOException
	 */
	public static List<String> filterMsg(List<KeyWordItem> kwList,List<String> fileList,
			List<KeyWordItem> addKwList,List<String> keyTimeList) throws IOException {
		
		//如有额外新添加的关键字，添加
		List<KeyWordItem> endKwList = new ArrayList<>();
		endKwList.addAll(kwList);
		if(!addKwList.isEmpty()) {
			endKwList.addAll(addKwList);
		}
		
		System.out.println("Total keywords:" + endKwList.toString());
		List<String> outputList = new ArrayList<>();
//		for(int i=fileList.size()-1;i>=0;i--)
		for(String filePath:fileList) 
		{
//			String filePath = fileList.get(i);
			File file = new File(filePath);
//			FileReader reader = new FileReader(file);
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
			BufferedReader bfr = new BufferedReader(isr);
			String line = "";
			boolean isPathPrint = false;//是否打印了文件路径
			while((line = bfr.readLine()) != null) {
				if(line.length() < 15) {
					continue;
				}
				String logHeadTime = line.substring(0, 15);//06-24 16:30
				//关键字查询是否符合条件
				if(isFilterLine(line,endKwList)) {
					boolean bret = isInTimeRange(keyTimeList,logHeadTime);
					if(bret) {
						//找到符合条件的文件，则打印该文件的文件名  全路径
						if(!isPathPrint) {
							System.out.println("/*************************************************/");
							outputList.add("/*************************************************/");
							
							System.out.println(filePath + "\n");
							outputList.add(filePath + "\n");
							isPathPrint = true;
						}
						//将前一行数据打印出来
						if(isShowNearLine) {
							System.out.println(preLine);
							outputList.add(preLine);
						}
						//将当前行打印出来
						System.out.println(line);
						outputList.add(line);
					}
				}
				preLine = line;
			}
			bfr.close();
			isr.close();
			fis.close();
//			reader.close();
		}
		return outputList;
	}
	
	/**
	 * 删除特定内容行
	 * @param kwList
	 * @param singleFile
	 * @return
	 * @throws IOException
	 */
	public static List<String> deleteMsg(List<KeyWordItem> kwList,String singleFile) throws IOException{
		File file = new File(singleFile);
		FileInputStream fis = new FileInputStream(file);
		InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
		BufferedReader bfr = new BufferedReader(isr);
		String line = "";
		List<String> outputList = new ArrayList<>();
		int rmLineNum = 0;
		while((line = bfr.readLine()) != null) {
			if(!isFilterLine(line,kwList)) {
				outputList.add(line);
			}else {
				rmLineNum++;
			}
		}
		bfr.close();
		isr.close();
		fis.close();
		System.out.println("共清除特定内容关键行数量:" + rmLineNum);
		return outputList;
	}
	
	/**
	 * 保存内容到文件
	 * @param list
	 * @param fname 为空则按照时间存储文件
	 * @throws IOException
	 */
	public static void saveContent(List<String> list,String fname) throws IOException {
		String path = System.getProperty("user.dir") + "\\" + System.currentTimeMillis() + ".txt";
		if(fname != null && !fname.isEmpty()) {
			path = System.getProperty("user.dir") + "\\" + fname;
		}
//		System.out.println(path);
		FileWriter writer = new FileWriter(new File(path));
		for(String line:list) {
			writer.write(line + "\n");
		}
		writer.close();
		System.out.println("结果已存储到-->" + path);
		savePath = path;
	}
	
	/**
	 * 最长20个字符
	 * @param in
	 * @return
	 */
	public static String formatString(String in) {
//		return String.format("%-15s", in);
		int inRealLen = 0;
		for(int i=0;i<in.length();i++) {
			if(isChinese(in.charAt(i))) {
				inRealLen += 2;
			}else {
				inRealLen += 1;
			}
		}
		String spaceStr = "";
		for(int i=inRealLen;i<20;i++) {
			spaceStr += " ";
		}
		return in + spaceStr;
	}
	
	/**
	 * 加载问题配置参数
	 */
	public static void loadQuestionsConfig() {
		Path path = Paths.get("config");
		FileVisitor fv = new FileVisitor();
		try {
			Files.walkFileTree(path, fv);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String baseDir = System.getProperty("user.dir") + File.separator;
		Integer idx = 1;
		for(String ss:fv.getFileSet()) {
			//ss = config\wifi.properties,qname = wifi
			String qName = ss.split("\\.")[0].substring("config".length()+1);
			Properties properties=new Properties();
			CmdBean cmdBean = new CmdBean(BaseFilter.getInstance(),qName);
	        try{
	        	InputStream in = new BufferedInputStream(new FileInputStream(baseDir + ss));
	            properties.load(new InputStreamReader(in, "UTF-8"));
	   	     	Iterator<String> it = properties.stringPropertyNames().iterator();
   	            while (it.hasNext()) {
   	                String key = it.next();
   	                //AR_KEY会打印出关键字的前后行数据
   	                if(key.contains("AR_KEY")) {
   	                	cmdBean.addKeyWord(properties.getProperty(key),true);
   	                }else {
   	   	                cmdBean.addKeyWord(properties.getProperty(key));
//   	                System.out.println(key + ":" + properties.getProperty(key));
   	                }

   	            }
   	            in.close();
   	            Const.pblMap.put(idx, cmdBean);
   	            idx++;
	        }catch(Exception e){
	            e.printStackTrace();
	        }
		}
		Const.pblMap.put(idx, new CmdBean(DeleteKeyword.class,"删除特定内容行"));
	}
	
	public static void loadParamsConfig() {
		Properties properties=new Properties();
		try{
        	InputStream in = new BufferedInputStream(new FileInputStream("params.properties"));
            properties.load(new InputStreamReader(in, "UTF-8"));
            Const.NOTEPAD_PATH = (String) properties.getProperty("NOTEPAD_PATH");
            
        }catch(Exception e){
            e.printStackTrace();
        }
	}
	
	private static boolean isChinese(char c) {
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(String.valueOf(c));
		return m.find();
	}
	
	/**
	 * 获取上次保存的路径名，用与notepad无参数时直接打开上次保存文件
	 */
	private static String savePath = "";
	public static String getSavePath() {
		return savePath;
	}
	
	/**
	 * 该行是否为过滤行
	 * @param line
	 * @param kwList
	 * @return   true是，过滤   false 不是，不过滤
	 */
	private static boolean isShowNearLine = false;
	private static boolean isFilterLine(String line,List<KeyWordItem> kwList) {
		//显示关键字后的一行内容
		if(isShowNearLine) {
			isShowNearLine = false;
			return true;
		}
		for(int i=0;i<kwList.size();i++) {
			if(line.contains(kwList.get(i).key)) {
				isShowNearLine = kwList.get(i).isShowNearLine;
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 是否在时间内
	 * @param list
	 * @param time
	 * @return
	 */
	private static boolean isInTimeRange(List<String> list,String time) {
		if(list.isEmpty() || list.get(0).isEmpty() || list.get(1).isEmpty()) {
			return true;
		}
		return list.get(0).compareTo(time) <= 0 && list.get(1).compareTo(time) >= 0;
	}
}
